package com.yksj.healthtalk.ui.login;

import java.io.File;
import java.io.FileNotFoundException;

import org.cropimage.CropUtils;
import org.universalimageloader.utils.StorageUtils;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog.OnClickSureBtnListener;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.PopWindowUtil;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;

public class UserProfileSettingUI extends BaseFragmentActivity implements OnClickListener {
	
	File headerFile;
	File cameFile;
	RadioGroup mSexGroup;
	EditText mNickName;
	ImageView mHeadView;
	
	@Override
	protected void onCreate(Bundle outState) {
		super.onCreate(outState);
		setContentView(R.layout.user_profile_setting_ui);
		
		initUI();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
		case 3000://相册获取
			if(resultCode == Activity.RESULT_OK){
				if (data != null) {
					Uri uri = data.getData();
					String scheme = uri.getScheme();
					String strFilePath = null;//图片地址
					// url类型content or file
					if ("content".equals(scheme)) {
						strFilePath = getImageUrlByAlbum(uri);
					} else {
						strFilePath = uri.getPath();
					}
					onHandlerCropImage(strFilePath);
				}
			}
			break;
		case 3001://相机获取
			if(resultCode == Activity.RESULT_OK){
				String strFilePath = cameFile.getAbsolutePath();
				onHandlerCropImage(strFilePath);
			}
			//cameFile = null;
			break;
		case 3002:
			if(resultCode == RESULT_OK){
				Bitmap bitmap = BitmapUtils.decodeBitmap(headerFile.getAbsolutePath(),
						CropUtils.HEADER_WIDTH,
						CropUtils.HEADER_HEIGTH);
				mHeadView.setImageBitmap(bitmap);
			}else{
				if(headerFile != null)headerFile.deleteOnExit();
				headerFile = null;
			}
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
	}
	
	private void initUI(){
		mHeadView = (ImageView)findViewById(R.id.user_head);
		mSexGroup = (RadioGroup)findViewById(R.id.sex);
		mHeadView.setOnClickListener(this);
		findViewById(R.id.btn_ok).setOnClickListener(this);
		Intent intent = getIntent();
		TextView textView = (TextView)findViewById(R.id.duomei_num);
		textView.setText(intent.getStringExtra("duomeinum"));
		mNickName = (EditText)findViewById(R.id.nick_name);
		mNickName.setText(getIntent().getStringExtra("duomeinum"));
	}
	
	/**
	 * 根据uri查询相册所对应的图片地址
	 * @param uri
	 * @return
	 */
	private String getImageUrlByAlbum(Uri uri) {
		String[] imageItems = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, imageItems, null, null, null);
		int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		String path = cursor.getString(index);
		return path;
	}
	
	/**
	 * 图片裁剪
	 * @param path
	 */
	private void onHandlerCropImage(String path){
		if(!SystemUtils.getScdExit()){
			ToastUtil.showSDCardBusy();
			return;
		}
		try{
			headerFile = StorageUtils.createHeaderFile();
			Uri outUri = Uri.fromFile(new File(path));
			Uri saveUri = Uri.fromFile(headerFile);
			Intent intent = CropUtils.createHeaderCropIntent(this,outUri,saveUri,true);
			startActivityForResult(intent,3002);
		}catch(Exception e){
			ToastUtil.showCreateFail();
		}
	}
	
	private void onChangeUserProfile(){
		RadioButton button  = (RadioButton)mSexGroup.findViewById(mSexGroup.getCheckedRadioButtonId());
		RequestParams params = new RequestParams();
		if(headerFile != null && !SystemUtils.getScdExit()){
			ToastUtil.showSDCardBusy();
			return;
		}
		if(TextUtils.isEmpty(mNickName.getEditableText())){
			mNickName.setError("昵称不能为空");
			return;
		}
		if(headerFile != null && headerFile.exists()){
			try {
				params.put("header", headerFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}else{
			params.putNullFile("header", new File(""));
		}
		TextView textView = (TextView)findViewById(R.id.nick_name);
		params.put("customerNickname",textView.getText().toString());
		params.put("customerSex",button.getText().equals("男") ? "1":"2");
		params.put("customerId",getIntent().getStringExtra("userid"));
		HttpRestClient.doHttpUpdateCustomerSexOrPic(params,new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				super.onSuccess(statusCode, response);
				if(response.containsKey(AsyncHttpResponseHandler.KEY_FAIL)){
					ToastUtil.showToastPanl(response.getString(AsyncHttpResponseHandler.KEY_FAIL));
				}else{
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), "修改成功",new OnClickSureBtnListener() {
						
						@Override
						public void onClickSureHander() {
							Intent intent = new Intent(UserProfileSettingUI.this,UserDoctorRegisteUI.class);
							intent.putExtras(getIntent().getExtras());
							startActivity(intent);							
						}
					});
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.btn_ok:
			onChangeUserProfile();
			break;
		case R.id.user_head:
			SystemUtils.hideSoftBord(this, mNickName);
			PopWindowUtil.showWindow(v,this,getLayoutInflater(),R.layout.personal_photo_check,this);
			break;
		case R.id.bendifenjian://本地
			try{
				if(!SystemUtils.getScdExit()){
					ToastUtil.showSDCardBusy();
					return;
				}
				Intent intent = CropUtils.createPickForFileIntent();
				startActivityForResult(intent,3000);
			}catch(Exception e){
				e.printStackTrace();
			}
			break;
		case R.id.paizhao://相机获取
			if(!SystemUtils.getScdExit()){
				ToastUtil.showSDCardBusy();
				return;
			}
			try {
				cameFile = StorageUtils.createImageFile();
				Uri outUri = Uri.fromFile(cameFile);
				Intent intent = CropUtils.createPickForCameraIntent(outUri);
				startActivityForResult(intent,3001);
			} catch (Exception e) {
				e.printStackTrace();
				ToastUtil.showCreateFail();
			}
			break;
		}
	}
}
